<template>
  <ElConfigProvider :locale="zhCn">
    <Suspense>
      <XMask
        :title="useTitle"
        :logo="useLogo || _logo"
        :menus="useMenus"
        :disabled="useDisabled"
        :actions="actions"
        :theme="useThemeSwitchable"
        @action-click="onActionClick"
      ></XMask>
    </Suspense>
  </ElConfigProvider>
</template>

<script setup lang="ts">
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Suspense, watchEffect, ref, computed, watch } from 'vue';
import { type MenuDataItem } from 'cfg-packages-ui';
import { ElConfigProvider, ElMessage } from 'element-plus';
import {
  XMask,
  // Bell, Lock, SwitchButton,
  type ActionBarItems,
  type ActionProps
} from 'cfg-packages-web';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import _logo from './assets/logo.svg';
import { useRoute } from 'vue-router';
import { useProvider } from 'cfg-packages-web';

const actions: ActionBarItems = [
  // {
  //   name: 'message',
  //   icon: Bell,
  //   badge: 1
  // },
  // {
  //   name: 'lock',
  //   icon: Lock
  // },
  // {
  //   name: 'logout',
  //   icon: SwitchButton
  // }
];
const onActionClick = (action: ActionProps) => {
  ElMessage.success(`click: ${action.name}`);
};

const provider = useProvider();
const route = useRoute();

/**
 * 生成menus菜单
 * @param pages
 * @param prjId
 */
const createMenus = (pages: any[] = [], prjId = ''): any => {
  return pages.map((page): any => {
    const { id, title, icon, children, hidden } = page;
    return {
      id,
      title,
      icon,
      hidden,
      url: prjId ? `/page/${id}/${prjId}` : `/page/${id}`,
      children: children && children.length ? createMenus(children, prjId) : undefined
    };
  });
};

/**
 * 初始化
 */
const init = async () => {
  try {
    const { name, params, meta } = route;
    params.prjId && (await provider.changeProject(params.prjId as string));
    // console.log('init', name, params.id, params.prjId, meta);
    if (name === 'CfgPage') {
      const page = provider.getPage(params.id as string);
      disabled.value = !page?.mask;
    } else if (name === 'CfgProjectList' || name === 'CfgStartup') {
      disabled.value = true;
    } else {
      disabled.value = !meta.mask;
    }
    const project = provider.project;
    updateProjectData(project);
  } catch (e) {
    throw new Error(`Error in init: ${e}`);
  }
};

/**
 * 更新项目相关的数据
 * @param project
 */
const updateProjectData = (project: any) => {
  // console.log('updateProjectData', project?.id, project?.name);
  menus.value = createMenus(project?.pages, project?.id);
  config.value = project?.config;
  title.value = config.value?.title || project?.name || 'CFG低代码平台';
  logo.value = config.value?.logo || '';
  themeSwitchable.value = config.value?.themeSwitchable;
};

const disabled = ref(false);
const menus = ref<MenuDataItem[]>([]);
const config = ref<any>(null);
const title = ref('');
const logo = ref('');
const themeSwitchable = ref(false);

const useDisabled = computed(() => disabled.value);
const useLogo = computed(() => logo.value);
const useThemeSwitchable = computed(() => themeSwitchable.value);
const useTitle = computed(() => title.value);
const useMenus: any = computed(() => menus.value);

watchEffect(async () => {
  await init().catch((e: any) => {
    console.error('Initialization error in watchEffect:', e);
  });
});

watch(
  () => route.fullPath,
  async (_newPath) => {
    if (_newPath.startsWith('/page/')) {
      await init().catch((e: any) => {
        console.error('Initialization error:', e);
      });
    }
  },
  { immediate: true }
);

init().catch((e: any) => {
  console.error('Initialization error:', e);
});
</script>
